package com.example.chatweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.chatweb.entity.*;
import com.example.chatweb.mapper.MultipleReportMapper;
import com.example.chatweb.repository.ArticleRepository;
import com.example.chatweb.request.OpinionRequest;
import com.example.chatweb.request.ReportRequest;
import com.example.chatweb.request.SavedReport;
import com.example.chatweb.service.ReportService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.example.chatweb.entity.MultipleReport;


import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ArticleRepository articleRepository;
    public List<Article> findArticleByKeyword(String keyWord, int pageNo, int pageSize) throws IOException {
//        return Arrays.asList(new Article("id", "articleT", "articleA", "articleText"));
        if (keyWord.length() == 0)
            return articleRepository.getList("article",
                    pageNo,
                    pageSize,
                    Article.class);
        else
            return articleRepository.getListByFields("article",
                Arrays.asList("articleId", "articleTitle", "articleAuthors", "articleLanguage", "articleYear", "articleText", "articleUrl"),
                keyWord,
                pageNo,
                pageSize,
                Article.class);
    }

    @Override
    public String generateReport(ReportRequest reportRequest) {
        RestTemplate restTemplate = new RestTemplate(createFactoryWithTimeout(15));
        String url = "http://172.21.50.190:20618/multi_doc_generate";
        // 测试对象
        String responseBodyTest = "{\"code\": 1, \"msg\": \"success\", \"data\": {\"content\": \"测试。\"}}";

        // 用于切换真实请求和测试对象的标志
        boolean useTestResponse = false;

        if (useTestResponse) {
            return responseBodyTest;
        }
        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, reportRequest, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                if (responseBody != null) {
                    return responseBody;  // 返回原始JSON字符串
                } else {
                    return "{\"code\":0,\"msg\":\"No data received!\"}";
                }
            } else {
                return "{\"code\":0,\"msg\":\"Failed to retrieve data. Status code: " + response.getStatusCode() + "\"}";
            }
        } catch (ResourceAccessException e) {
            return "{\"code\":0,\"msg\":\"Request timed out!\"}";
        }
    }
    private HttpComponentsClientHttpRequestFactory createFactoryWithTimeout(int timeoutMinutes) {
        int timeout = (int) TimeUnit.MINUTES.toMillis(timeoutMinutes);

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(timeout);
        factory.setReadTimeout(timeout);

        return factory;
    }

    @Override
    public String extractOpinion(OpinionRequest opinionRequest) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://172.21.50.190:1133/extraction";
        ResponseEntity<String> response = restTemplate.postForEntity(url, opinionRequest, String.class);
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode jsonObj = mapper.readTree(response.getBody());
//            System.out.println("Data: " + jsonObj.get("data").asText());
            return jsonObj.get("data").asText();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("No data received!");
            return "No data received!";
        }
//        if (response.getStatusCode() == HttpStatus.OK) {
//            OpinionResponse apiResponse = response.getBody();
//            if (apiResponse != null ) {
//                String data = apiResponse.getData();
//                System.out.println("Opinion: " + data);
//
//                return data;
//            } else {
//                System.out.println("No data received!");
//                return "No data received!";
//            }
//        } else {
//            System.out.println("Failed to retrieve data. Status code: " + response.getStatusCode());
//            return "No data received!";
//        }
//        System.out.println(response);
//        return response.getBody();
    }
    @Autowired
    private MultipleReportMapper multipleReportMapper;


    @Override
    public String uploadToDB(SavedReport savedReport) {
        String reportId = savedReport.getReportId(); // 获取传回的报告 ID
        //System.out.println(reportId);
        if ("new".equals(reportId)) { // 判断 reportId 是否为 "new"
            reportId = UUID.randomUUID().toString(); // 生成唯一的报告 ID
        } else {
            // 删除数据库中 reportId 等于传回 id 的数据项
            multipleReportMapper.delete(new QueryWrapper<MultipleReport>().eq("report_id", reportId));
        }
        //System.out.println(reportId);
        // 保存新的报告数据
        for (SavedReport.Chapter chapter : savedReport.getChapters()) {
            MultipleReport report = new MultipleReport();
            report.setUserId(savedReport.getUserId());
            report.setReportId(reportId);
            report.setReportTopic(savedReport.getTopic());
            report.setChapterTitle(chapter.getTitle());
            report.setChapterContent(chapter.getContent());
            multipleReportMapper.insert(report);
        }

        return "Report saved successfully";
    }
    @Override
    public String getReportContentByReportId(String reportId) {
        // 从数据库中检索指定 report_id 的所有记录
        List<MultipleReport> reports = multipleReportMapper.selectList(new QueryWrapper<MultipleReport>()
                .eq("report_id", reportId)
                .orderByAsc("id")); // 假设记录按 id 排序，根据实际情况调整排序字段

        // 处理数据并转换成 JSON 格式
        JSONObject jsonReport = new JSONObject();
        jsonReport.put("user_id", reports.get(0).getUserId());
        jsonReport.put("topic", reports.get(0).getReportTopic());

        JSONArray chapters = new JSONArray();
        for (MultipleReport report : reports) {
            JSONObject chapter = new JSONObject();
            chapter.put("title", report.getChapterTitle());
            chapter.put("content", report.getChapterContent());
            chapters.put(chapter);
        }
        jsonReport.put("chapters", chapters);

        // 返回 JSON 字符串给前端
        System.out.println(jsonReport);
        return jsonReport.toString();
    }

    @Override
    public String getEveryReportIDByUserid(String userId) {
        // 从数据库中检索指定 user_id 的所有 report_id 和 report_topic
        List<MultipleReport> reports = multipleReportMapper.selectList(new QueryWrapper<MultipleReport>()
                .eq("user_id", userId));

        // 使用 HashMap 去重并保留 report_id 和 report_topic
        Map<String, String> uniqueReports = new HashMap<>();
        for (MultipleReport report : reports) {
            uniqueReports.put(report.getReportId(), report.getReportTopic());
        }

        // 构造 JSON 格式
        JSONObject jsonResult = new JSONObject();
        jsonResult.put("user_id", userId);

        JSONArray reportIdsArray = new JSONArray();
        for (Map.Entry<String, String> entry : uniqueReports.entrySet()) {
            JSONObject reportIdObject = new JSONObject();
            reportIdObject.put("report_id", entry.getKey());
            reportIdObject.put("report_topic", entry.getValue());
            reportIdsArray.put(reportIdObject); // 使用 put 方法
        }
        jsonResult.put("report_ids", reportIdsArray);

        // 返回 JSON 字符串给前端
        System.out.println(jsonResult);
        return jsonResult.toString();
    }

}
